package com.example.webapp.controler;

import com.example.webapp.bean.*;
import com.example.webapp.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;


@Controller
public class SearchScoreControler {
    @Autowired
    private StudentExamService studentExamService;
    @Autowired
    private ExamService examService;
    @Autowired
    private UserService userService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private RegistrationService registrationService;

    @CrossOrigin
    @PostMapping("/searchscore")
    @ResponseBody
    public String getscore(@RequestBody Map map){
        String UidStr=(String)map.get("uid");
        Integer Uid=Integer.parseInt(UidStr);
        Optional<User> nowUser=userService.selectUserid(Uid);
        User ExamUser;
        if (!nowUser.isPresent()) {
            return "no user";
        } else {
            ExamUser=nowUser.get();
        }

        List<Registration> StudentRegistration=registrationService.findRegistrationsByStudent_Id(Uid);
        String TestObjectsStr="[";
        if(StudentRegistration==null||StudentRegistration.size()==0)
            return"[]";
        for(int i=0;i<StudentRegistration.size();i++){
            Integer nowScore=0;
            Exam nowExam=StudentRegistration.get(i).getExam();
            List<StudentExam> StudentExamLog=studentExamService.findStudentExamsByStudentAndExam(ExamUser,nowExam);
            TestObjectsStr+="{"+"\"exam\":"+"\""+StudentRegistration.get(i).getExam().getName()+"\""+
                    ","+"\"name\":"+"\""+StudentRegistration.get(i).getStudent().getName()+"\""+",";
            if(StudentExamLog==null||StudentExamLog.size()==0){
                TestObjectsStr+="\"score\":"+"\"未参加考试\""+"}";
                if(i!=StudentRegistration.size()-1){
                    TestObjectsStr+=",";
                }
            }
            else {
                for (int j = 0; j < StudentExamLog.size(); j++) {
                    nowScore += StudentExamLog.get(j).getScore_get();
                    //System.out.println(StudentExamLog.get(j).getScore_get());
                }
                TestObjectsStr += "\"score\":" + nowScore.toString() + "}";
                if(i!=StudentRegistration.size()-1){
                    TestObjectsStr+=",";
                }
            }
        }
        TestObjectsStr+="]";


        return TestObjectsStr;
    }
}